import json
import random
import re
import time
import uuid

import requests
from qiniu import Auth

from newpro.db import db
from newpro.util.SmsTool import send
from newpro.util.myjwt import myjwt
from newpro.util.myredis import r
from newpro.views.base import BaseHandler
from newpro.util.captcha.captcha import captcha
from newpro.views.user import getMenu, getinterfacelist
from newpro.util.bd import bd

# 获取图片验证码
class Picture(BaseHandler):
    def get(self):
        uuid = self.get_query_argument("uuid")
        name, text, img = captcha.generate_captcha()
        r.set_str(uuid, text)
        self.set_header("Content-Type", "image/jpg")
        self.write(img)

# 获取验证码
class SmsHandler(BaseHandler):
    def post(self):
        data = self.request.body
        mes = json.loads(data)
        phone = mes['phone']
        image = mes['image']
        uuid = mes['uuid']
        if not all([phone, image, uuid]):
            self.finish({'code': 401, 'mag': '手机号或图片验证码未输入'})
        res = re.findall(r'^1[3-9][0-9]{9}$', phone)
        if not res:
            self.finish({'code': 402, 'msg': '手机号输入错误'})

        uu_res = r.str_get(uuid)
        if uuid:
            uu = uu_res.decode()
        else:
            self.finish({'code': 403, 'msg': '图片验证码输入错误'})
        if uu.lower() != image.lower():
            self.finish({'code': 404, 'msg': '图片验证码输入错误'})

        code = random.randint(1000, 9999)
        rs = send(phone)
        if rs:
            self.finish({'code': 200, 'msg': '验证码发送成功'})
        else:
            self.finish({'code': 405, 'msg': '发送失败'})

class RegisterHandler(BaseHandler):
    def post(self):
        data = self.request.body
        mes = json.loads(data)
        phone = mes['phone']
        sms = mes['sms']
        newsms = r.str_get("sms_%s" % phone)
        # 校验验证码是否过期
        if not newsms:
            self.finish({'code': 400, 'msg': '验证码已过期'})
        # 校验验证码是否正确
        if sms != newsms.decode():
            self.finish({'code': 400, 'msg': '验证码错误'})
        sql = "select id from user where phone='%s'" % phone
        user_info = db.findOne(sql)
        if not user_info:
            add_sql = "insert into user(phone) values (%s)" % phone
            db.add(add_sql)
            db.commit()
        sql = "select id from user where phone='%s'" % phone
        user_info = db.findOne(sql)
        data = {'data': {'userid': user_info['id'], 'phone': ['phone'], 'ex': int(time.time())}}
        token = myjwt.jwt_en(data)
        sql1 = "select * from user where phone='%s'" % phone
        res = db.findOne(sql1)
        if res:
            self.finish({'code': 200, 'token': token, 'userid': user_info['id'], 'msg': '登陆成功'})
        else:
            self.finish({'code': 400, 'msg': '登陆失败'})


class Sina(BaseHandler):
    def get(self):
        # App Key   应用ID
        client_id = "3674019597"
        # App Secret
        client_secret = "7ae99bc0d54ead29fc8d1b9fabd78587"
        # 微博回调网址
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        # 微博跳转网址
        sina_url = "https://api.weibo.com/oauth2/authorize"

        auth_url = sina_url + f"?client_id={client_id}&redirect_uri={redirect_uri}"

        # 返回跳转地址
        self.finish({'code': 200, "url": auth_url})

class Sina_Login(BaseHandler):
    def get(self):
        code = self.get_query_argument("code")
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res1 = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        mes = json.loads(res1.text)
        uid = mes['uid']
        token = mes['access_token']
        sql = "select u.id,u.phone from user as u inner join sf_login as sl on u.id=sl.userid where sl.uid='%s'" % uid
        user = db.findOne(sql)
        if user:
            token = myjwt.jwt_en(data={"data": {'uid': user['id'], 'phone': user['phone'], 'ex': int(time.time())}})
            self.redirect("http://localhost:8080/updatetoken?token=" + token + "&userid=" + str(user['id']))
        else:
            self.redirect("http://localhost:8080/bangMobile?uid="+uid+"&token="+token)

    def post(self):
        data = json.loads(self.request.body)
        phone = data['phone']
        uid = data['uid']
        token = data['token']
        add_spl = "insert into user(phone) values(%s) " % (phone)
        userid = db.add(add_spl)
        sql = "select * from user where phone=%s"%phone
        res = db.findOne(sql)
        if res:
            ad_sql = "insert into sf_login(userid, webfrom, token, uid) values(%d,'weibo','%s','%s')"%(userid, token, uid)
            db.add(ad_sql)
            db.commit()
        token = myjwt.jwt_en(data={"data": {"uid": userid, "phone": data['phone'], 'exp': int(time.time())}})
        return self.finish({"code": 200, "token": token, "userid": userid})


class Qiniuyun(BaseHandler):
    def get(self):
        access_key = '8Tm9dbiS7igO2nzGj8rPe8IADuqCdpkYyUSH7wgF'
        secret_key = '_Qzo5Lu-6-zIzsHlquyAyTTppwlAJzc2I0owZqCj'
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'p2p1'
        key = int(time.time())
        token = q.upload_token(bucket_name)
        return self.finish({'code': 200, 'token': token})


class Getbaidu(BaseHandler):
    def get(self):
        url = self.get_query_argument('url')
        a = bd.getmes(urlmes=url)

        return self.finish({'code': 200, 'data': a})




